/**
 * JAVACC DEMO 1.0
 */
package com.apache.ius.able;

import java.util.concurrent.*;

/**
 * description:  线程池调度
 * @author qihan 创建时间：2017-10-19
 */
public class ScheduledExecutor {

	private static ScheduledExecutor instance;
	private final static String OBJ ="1";

	private ThreadPoolExecutor service;

	private ScheduledExecutor() {
	}

	/**
	 * description:  创建单实例方法
	 * @return
	 * @author Hou Dayu
	 * @update 2015-1-14
	 */
	public synchronized static ScheduledExecutor instance() {
		if (null == instance) {
			instance = new ScheduledExecutor();
		}
		return instance;
	}

	public ExecutorService getService(int size) {
		return new ThreadPoolExecutor(size, size, 20, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(size));
	}

	public Future<Integer> submit(Callable<Integer> task) {
		initThreadPool();
		return service.submit(task);
	}

	public Future<Object> submitObj(Callable<Object> task) {
		initThreadPool();
		return service.submit(task);
	}

	public void runable(Runnable task) {
		initThreadPool();
		service.submit(task);
	}

	public void shutdown() {
		if(null == service) {
			service.shutdown();
		}
	}

	private void initThreadPool(){
		synchronized (OBJ) {
			if (null == service) {
				service = new ThreadPoolExecutor(10, 20, 60, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10));
				service.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
			}
		}
	}
}
